package com.vend.common_lib.retrofithttp;
import com.vend.common.retrofithttp.RetrofitConfig
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by glendal on 2022/01/13.
 * 创建Retorift管理器
 */
class RetrofitHttpManager {
    private val DEFAULT_CONNECT_TIME = 10
    private val DEFAULT_WRITE_TIME = 30
    private val DEFAULT_READ_TIME = 30
    private var retrofit =  Retrofit.Builder()
        .client(getLogClient()) //设置使用okhttp网络请求
        .baseUrl(RetrofitConfig.httpHost + RetrofitConfig.sSubPrefix) //设置服务器路径
        .addConverterFactory(GsonConverterFactory.create()) //添加转化库，默认是Gson
//        .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) //添加回调库，采用RxJava
        .build()


    /**
     * 单利模式
     */
    companion object{
        val instance = ManagerSingle.mRetrofit
        private var mInterceptor = ArrayList<Interceptor>()
        /**
         * 设置头部拦截器
         * 这个必须在单利模式之前去创建
         */
        fun setInterceptor(list : List<Interceptor>){
            mInterceptor.clear()
            for (i in list){
                mInterceptor.add(i)
            }
        }
    }
    private object ManagerSingle{
        val mRetrofit = RetrofitHttpManager()
    }
    private fun getLogClient(): OkHttpClient? {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        val builder = OkHttpClient.Builder()
            .readTimeout(120, TimeUnit.SECONDS) //链接成功后读取信息最长是120s
            .writeTimeout(65, TimeUnit.SECONDS)
            .connectTimeout(20, TimeUnit.SECONDS)

        // 先添加其他的拦截器
        if (mInterceptor != null) {
            for (interceptor in mInterceptor) {
                builder.addInterceptor(interceptor)
            }
        }
        builder.addInterceptor(loggingInterceptor)
        builder.hostnameVerifier { hostname, session -> true }
        return builder.build()
//       val okHttpClient = OkHttpClient.Builder()
//            .connectTimeout(
//                DEFAULT_CONNECT_TIME.toLong(),
//                TimeUnit.SECONDS
//            ) //连接超时时间
//            .writeTimeout(
//                DEFAULT_WRITE_TIME.toLong(),
//                TimeUnit.SECONDS
//            ) //设置写操作超时时间
//            .readTimeout(
//                DEFAULT_READ_TIME.toLong(),
//                TimeUnit.SECONDS
//            ) //设置读操作超时时间
//            .build()
//        return okHttpClient
    }

    /**
     * 所有的类的创建
     */
    fun <T> create(service: Class<T>?): T {
        return retrofit.create(service)
    }
}